import store from '@/store'
import { signfn } from '@/utils/index.js'

// 初始化请求配置
uni.$u.http.setConfig((config) => {
	config.baseURL = process.env['HTTP_URL']
	config.header = {
		'Content-Type': 'application/json;charset=UTF-8'
	}
	config.timeout = 60000
	config.custom = {
		load: true, //是否显示加载动画
	}
	return config
})

// 请求拦截
uni.$u.http.interceptors.request.use((config) => {
	const token = uni.getStorageSync('token')
	const signInfo = signfn(config.url)
	config.header = {
		...config.header,
		...signInfo,
	}
	if (token) config.header['auth-access-token'] = token
	if (config?.custom?.load && !store.state.loadingShow) {
		//打开加载动画
		store.state.loadingShow = true
	}
	return config
}, config => {
	return Promise.reject(config)
})

// 响应拦截
const loginErrorCode = []
uni.$u.http.interceptors.response.use((response) => {
	// 关闭加载动画
	store.state.loadingShow = false
	if (loginErrorCode.includes(response.data.result.status_info.status_code)) {
		uni.showToast({
			title: '身份已过期,请重新登录',
			icon: 'none',
			complete: () => {
				setTimeout(() => {
					uni.removeStorageSync('token')
					uni.reLaunch({
						url: `/pages/login/index`
					})
				}, 1000)

			}
		})
	}
	return response.data
}, (response) => {
	uni.showToast({
		title: '网络超时了，请检查当前网络后重试',
		icon: 'none'
	})
	store.state.loadingShow = false
	return Promise.reject(response)
})